package com.winit.cloudlink.mgmt.rabbit;

import com.winit.cloudlink.common.URL;
import com.winit.cloudlink.rabbitmq.mgmt.RabbitMgmtService;
import com.winit.cloudlink.rabbitmq.mgmt.model.Binding;
import com.winit.cloudlink.rabbitmq.mgmt.model.Queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

import static org.apache.commons.lang3.StringUtils.isBlank;


/**
 * Created by stvli on 2017/3/31.
 */
public class QueueAdmin extends BaseAdmin {
    private static Logger logger = LoggerFactory.getLogger(QueueAdmin.class);

    public QueueAdmin(URL url) {
        super(url);
    }

    public QueueAdmin(RabbitMgmtService rabbitMgmtService, String virtualHost) {
        super(rabbitMgmtService, virtualHost);
    }

    public Collection<Queue> queryQueries() {
        return rabbitMgmtService.queues().allOnVHost(virtualHost).get();
    }

    public Collection<Queue> queryQueries(String queueName) {
        return rabbitMgmtService.queues().get(virtualHost, queueName).asSet();
    }

    public Collection<Binding> queryQueryBinds(String queueName) {
        return rabbitMgmtService.queues().bindings(virtualHost, queueName).get();
    }

    public void declarationQueue(Queue queue, Collection<Binding> bindings) {
        queue.setVhost(virtualHost);
        rabbitMgmtService.queues().create(queue);
        String queueName = queue.getName();
        for (Binding binding : bindings) {
            if (isBlank(binding.getSource())) {
                continue;
            }
            String exchangeName = binding.getSource();
            String routingKey = binding.getRoutingKey();
            Binding destinationBinding = new Binding(exchangeName, queueName, routingKey);
            destinationBinding.setVhost(virtualHost);
            rabbitMgmtService.bindings().create(destinationBinding);
        }
    }
}
